<template>
	<view class="w-1 p-30">
		<view class="fl-s-s bg-ff br-20 ">
			<view class="w-1 fr-s-c"  style="padding: 30rpx 20rpx;" @click="$to('/pages/User/Address/Address?choose=1&ekey=setads')">
				<view class="flex-1" :class="ainfo?'fl-s-s':'fr-s-c'">
					<block v-if="ainfo">
						<view class="fr-s-c">
							<up-icon name="map-fill" color="#01796d"></up-icon>
							<text class="flex-1 t-r c-33 fs-24 m-l-10" >{{ainfo.residevice + ainfo.residecity+ ainfo.residedist}}</text>
						</view>
						<view class="fr-s-c m-t-10">
							<view style="opacity: 0;">
								<up-icon style="opacity: 0;" name="map-fill" color="#01796d"></up-icon>
							</view>
							<text class="m-l-10 c-33 fs-32 bold">{{ainfo.address}}</text>
						</view>
						<view class="fr-s-c m-t-10">
							<view style="opacity: 0;">
								<up-icon style="opacity: 0;" name="map-fill" color="#01796d"></up-icon>
							</view>
							<text class="c-33 fs-24 m-l-10">{{ainfo.name+'（'+ainfo.tel+'）'}}</text>
						</view>
						
					</block>
					<block v-else>
						<text class="c-33 fs-32 bold">上门地址</text>
						<text class="flex-1 t-r c-99 fs-30">请选择上门地址</text>
					</block>
				</view>
				<up-icon name="arrow-right"></up-icon>
			</view>
			<view class="w-1 bb-solid"></view>
			<view class="w-1 fr-b-c"  @click="showtime" style="padding: 30rpx 20rpx;">
				<view class="fr-s-c">
					<up-icon size="30rpx" name="clock"></up-icon>
					<text class="c-33 m-l-10 fs-24">期望上门时间</text>
				</view>
				<view class="fr-s-c">
					<text class="c-77 m-l-10 fs-24">{{form.reservtime}}</text>
					<up-icon size="30rpx" name="arrow-right"></up-icon>
				</view>
			</view>
		</view>
		<!-- 单商品 -->
		<view class="w-1 bg-ff m-t-30 br-20 fl-s-s" v-if="info">
			<view class="fr-s-c w-1 p-30">
				<image class="br-20" style="width: 160rpx; height: 160rpx;" :src="$dimg(info.image)" mode="aspectFill">
				</image>
				<view class="flex-1 fl-b-s m-l-25" style="height: 160rpx;">
					<text class="text-line-1 c-33 bold fs-30">{{info.title}}</text>
					<text class="text-line-1 fs-24 c-77" v-if="form.sku">规格：{{form.sku}}</text>
					<!-- <view class="w-1 fr-b-c">
						<text class="c-price fs-28 bold">￥{{info.price}}</text>
						<text class="c-66 fs-28">x{{form.num}}</text>
					</view> -->
				</view>
			</view>
			<view class="w-1 bb-solid fr-s-c" style="padding: 20rpx 30rpx;">
				<text class="c-33 fs-28 bold">数量</text>
				<text class="fs-28 flex-1 bold t-r c-33">x{{form.num}}</text>
			</view>
			<view class="w-1 fr-s-c bb-solid" style="padding: 20rpx 30rpx;">
				<text class="c-33 fs-28 bold">服务费用</text>
				<text class="fs-28 flex-1 bold t-r c-33">{{form.price}}元</text>
			</view>
			<view class="w-1 fr-s-c" @click="$u.route('/pages/User/MyCoupon?choose=1')" style="padding: 20rpx 30rpx;">
				<text class="c-33 fs-28 bold">优惠券</text>
				<text class="fs-28 flex-1 bold t-r c-price" v-if="cinfo">-￥{{cinfo.price}}元</text>
				<text class="flex-1" v-else></text>
				<up-icon name="arrow-right"></up-icon>
			</view>
		</view>
		
		<!-- <view class="w-1 br-20 bg-ff m-t-20 p-30 fl-s-s">
			<text class="c-00 fs-28 bold m-b-20">需求填报</text>
			<view v-if="vinfo" class="fl-c relative br-20" style="width: 136rpx; height: 136rpx; background: #f3f3f3;">
				<image :src="vinfo.thumbTempFilePath" class="w-1 h-1 br-20" mode="aspectFill"></image>
				<view class="w-1 h-1 absolute-0 fl-b-e br-20 o-h" style="padding: 10rpx;">
					<up-icon name="close-circle" @click="(vinfo='',form.environask='',form.envimage='')" color="#ffffff" size="35rpx"></up-icon>
					<view class="w-1 fr-c" @click="lookvideo">
						<up-icon name="play-right-fill" size="50rpx" color="#ffffff"></up-icon>
					</view>
					<view style="opacity: 0;">
						<up-icon hidden name="close-circle" color="#ffffff" size="35rpx"></up-icon>
					</view>
				</view>
			</view>
			<view v-else @click="choosevideo" class="fl-c br-20" style="width: 136rpx; height: 136rpx; background: #f3f3f3;">
				<image :src="$path + '/tab1/camera.png'" style="width: 51rpx; height: 49rpx;" mode=""></image>
				<text class="fs-20 c-77">上传视频</text>
			</view>
		</view> -->
		<view class="w-1 br-20 bg-ff m-t-20 p-30 fl-s-s">
			<text class="c-00 fs-28 bold m-b-20">需求填报（视频和图片根据需求自行上传）</text>
			<textarea class="qt fs-24 p-30" v-model="form.remark" disable-default-padding placeholder="请描述您遇到的问题"></textarea>
			<view class="w-1 m-t-20 fr-s-s">
				<view class="" v-if="!vinfo">
					<up-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" :multiple="true"
						width="136rpx" height="136rpx" :maxCount="6">
						<view class="fl-c br-20" style="width: 136rpx; height: 136rpx; background: #f3f3f3;">
							<image :src="$path + '/tab1/camera.png'" style="width: 51rpx; height: 49rpx;" mode=""></image>
							<text class="fs-20 c-77">上传图片</text>
						</view>
					</up-upload>
				</view>
				<block v-if="!fileList1.length">
					<view class="m-l-20" v-if="!vinfo && !fileList1.length"></view>
					<view class="">
						<view v-if="vinfo" class="fl-c relative br-20" style="width: 136rpx; height: 136rpx; background: #f3f3f3;">
							<!-- tempFilePath -->
							<image :src="vinfo.thumbTempFilePath" class="w-1 h-1 br-20" mode="aspectFill"></image>
							<view class="w-1 h-1 absolute-0 fl-b-e br-20 o-h" style="padding: 10rpx;">
								<up-icon name="close-circle" @click="(vinfo='',form.environask='',form.envimage='')" color="#ffffff" size="35rpx"></up-icon>
								<view class="w-1 fr-c" @click="lookvideo">
									<up-icon name="play-right-fill" size="50rpx" color="#ffffff"></up-icon>
								</view>
								<view style="opacity: 0;">
									<up-icon hidden name="close-circle" color="#ffffff" size="35rpx"></up-icon>
								</view>
							</view>
						</view>
						<view v-else @click="choosevideo" class="fl-c br-20" style="width: 136rpx; height: 136rpx; background: #f3f3f3;">
							<image :src="$path + '/tab1/camera.png'" style="width: 51rpx; height: 49rpx;" mode=""></image>
							<text class="fs-20 c-77">上传视频</text>
						</view>
					</view>
				</block>
				
			</view>
			
		</view>
		
		<view class="w-1 bg-ff br-20 m-t-20" v-if="info.itionalmation && info.itionalmation.length">
			<view class="fr-s-c w-1" :class="index==info.itionalmation.length-1?'':'bb-solid'" v-for="(item,index) in info.itionalmation" :key="index" style="padding: 20rpx 30rpx;">
				<text class="fs-28 bold c-33">{{item}}</text>
				<input type="text" class="flex-1 fs-28 m-l-20" v-model="objs[item]" :placeholder="`请输入${item}`" />
			</view>
		</view>
		
		
		<view class="w-1 br-20 bg-ff m-t-20 p-30 fl-s-s" v-if="info.itionalmationimgs">
			<text class="c-00 fs-28 bold">{{info.itionalmationimgs}}（{{fileList2.length}}/5)</text>
			<view class="w-1 m-t-20">
				<up-upload :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2" :multiple="true"
					width="136rpx" height="136rpx" :maxCount="5">
					<view class="fl-c br-20" style="width: 136rpx; height: 136rpx; background: #f3f3f3;">
						<image :src="$path + '/tab1/camera.png'" style="width: 51rpx; height: 49rpx;" mode=""></image>
						<text class="fs-20 c-77">上传图片</text>
					</view>
				</up-upload>
			</view>
		</view>

		<view class="w-1 fr-b-c bg-ff m-t-20 p-30 br-20">
			<text class="c-33 fs-28 bold flex-1">支付方式</text>
			<image style="width: 52rpx; height: 47rpx;" :src="$path + '/tab1/wxpay.png'" mode=""></image>
			<text class="c-33 fs-28 bold m-l-20">微信</text>
		</view>

		<view style="height: 250rpx;"></view>
		<view class="w-1 bg-ff iphonex">
			<view class="w-1 p-30 fr-s-c">
				<view class="flex-1 fl-s-s">
					<view class="fr-s-c">
						<text class="c-33 fs-28">合计</text>
						<view class="c-price bold flex-1">
							<text class="fs-28">￥</text>
							<text class="fs-28">{{account}}</text>
						</view>
					</view>
					<text v-if="cinfo" class="c-price fs-20">优惠共减￥{{cinfo.price}}</text>
				</view>
				

				<view class="big-btn bold" style="width: 202rpx; height: 72rpx;" @click="sub">立即结算</view>
			</view>

	
			<up-popup v-model:show="show" closeable round="20rpx">
				<view class="w-1 fl-s-c">
					<text class="c-00 p-30 fs-32 bold">期望上门时间</text>
					<view class="w-1 fr-s-s">
						<scroll-view scroll-y="true" class="" style="width: 332rpx; height: 645rpx;" >
							<view class="fr-c" @click="(curd=index,ctitle='',showtime())" :class="curd==index?'lboxact':'lbox'" v-for="(item,index) in dlist" :key="index">{{item.title}}</view>
						</scroll-view>
						<scroll-view scroll-y="true" class="flex-1" style="height: 645rpx; padding-left: 20rpx;" >
							<block v-for="(item,index) in rlist" :key="index">
								<view class="fl-s-s" v-if="item.show">
									<text class="c-00 fs-28 bold m-b-20" >{{item.title}}</text>
									<block v-for="(items,indexs) in item.child" :key="indexs">
										<view v-if="items.show" :class="ctitle==items.title?'rboxact':'rbox'" @click="ctitle=items.title" class="fr-c m-b-20" >{{items.title}}</view>
									</block>
								</view>
							</block>
						</scroll-view>
					</view>
					<view class="p-30 fr-b-c w-1" style="box-shadow: 0rpx -6rpx 8rpx 2rpx rgba(0,0,0,0.07);">
						<view class="cancel fr-c" @click="show=false">取消</view>
						<view class="sure fr-c" @click="suredatetime">确定</view>
					</view>
				</view>
			</up-popup>

		</view>
		<!-- <paypop ref="pay" @confirm="confirmpay" :price="account"></paypop> -->
	</view>
</template>

<script setup>
	
	import {
		baseUrl
	} from '@/utils/base.js';
	const fileList1 = ref([]);
	watch(fileList1, val => {
		console.log('图片val', val)
		let arr = []
		val.map(item => {
			if (item.status == 'success') {
				// arr.push('/uploads/' + item.url.split('/uploads/')[1])
				arr.push(item.url)
			}
		})
		form.value.remarkimg = arr.join(',')
	}, {
		deep: true
	})
	
	const fileList2 = ref([]);
	const itionalmationimgs = ref('');  // 其他补充的图片
	watch(fileList2, val => {
		console.log('图片val', val)
		let arr = []
		val.map(item => {
			if (item.status == 'success') {
				// arr.push('/uploads/' + item.url.split('/uploads/')[1])
				arr.push(item.url)
			}
		})
		itionalmationimgs.value = arr.join(',')
	}, {
		deep: true
	})
	
	const vinfo = ref('')
	function choosevideo(){
		uni.chooseMedia({
		  count: 1,
		  mediaType: ['video'],
		  sourceType: ['album', 'camera'],
		  maxDuration: 60,
		  camera: 'back',
		  success:async (res)=> {
			console.log(res)
		    console.log(res.tempFiles)
			vinfo.value = res.tempFiles[0]
			const ret = await uni.$up({
				// [视频,封面]
				imageUrl:[res.tempFiles[0].tempFilePath,res.tempFiles[0].thumbTempFilePath]
			})
			uni.hideLoading()
			console.log(ret)
			form.value.environask = ret[0].fullurl  // 视频链接
			form.value.envimage = ret[1].fullurl // 视频封面图
		  }
		})
	}
	function lookvideo(){
		uni.navigateTo({
			url:'/pages/lookvideo?src='+encodeURIComponent(vinfo.value.tempFilePath)
		})
	}
	
	
	
	const cur = ref(1)
	
	

	const form = ref({
		remark: '',
		did: '',
		reservtime:'',
		envimage:'', // 视频封面图
		environask:'',  // 视频链接
		remarkimg:'',  // 需求填报图
		yid:'',
		sku:''
	})
	const goods = ref([])
	const info = ref('')
	const dlist = ref([])
	const curd = ref(0)
	onLoad(o => {
		form.value = {
			...form.value,
			...JSON.parse(decodeURIComponent(o.form))
		}
		getinfo()
		getainfo()
		getFormattedDates()
		console.log(form.value)
		
		
		uni.$on('setads', setainfo)
		uni.$on('setcoupon', setcinfo)
	})
	onUnload(() => {
		uni.$off('setads')
		uni.$off('setcoupon')
	})
	
	const cinfo = ref('');  // 优惠券信息
	function setcinfo(val){
		console.log(val)
		cinfo.value = val;
		form.value.yid = val.id
	}
	
	
	// 左侧日期
	function getFormattedDates() {
	    const today = new Date();
	    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
	    const dates = [];
	    for (let i = 0; i < 7; i++) {
	        const date = new Date(today);
	        date.setDate(today.getDate() + i);
			const year = date.getFullYear()
	        const month = (date.getMonth() + 1).toString().padStart(2, '0');
	        const day = date.getDate().toString().padStart(2, '0');
	        let label;
			const weekDay = weekDays[date.getDay()];
	        if (i === 0) {
	            label = '今天';
	        } else if (i === 1) {
	            label = '明天';
	        } else {
	            label = `周${weekDay}`;
	        }
	
	        dates.push({
				title:`${month}月${day}日(${label})`,
				val:year+'-'+month+'-'+day,
				name:`${month}月${day}日(周${weekDay})`
			});
	    }
		dlist.value = dates;
	    // return dates;
	}
	
	
	// 右侧时间
	const rlist = ref([
		{
			title:'上午',
			show:true,
			child:[{ 
				title:'08:00~10:00',
				show:true,
			},{
				title:'10:00~12:00',
				show:true,
			}]
		},{
			title:'下午',
			show:true,
			child:[{
				title:'12:00~14:00',
				show:true,
			},{
				title:'14:00~16:00',
				show:true,
			},{
				title:'16:00~18:00',
				show:true,
			}]
		},{
			title:'晚上',
			show:true,
			child:[{
				title:'18:00~20:00',
				show:true,
			},{
				title:'20:00~22:00',
				show:true,
			},{
				title:'22:00~24:00',
				show:true,
			}]
		}
	])
	
	import { timeFormat } from '@/uni_modules/uview-plus';
	function showtime(){
		let date = timeFormat(Date.now())
		let hm = timeFormat(Date.now(),'hh:MM')
		console.log(date)
		console.log(hm)
		if(curd.value==0){
			if(hm>'12:00'){
				rlist.value[0].show=false;
			}else{
				rlist.value[0].child.map(i=>{
					i.show = i.title.split('~')[1]>hm;
				})
			}
			if(hm>'18:00'){
				rlist.value[1].show=false;
			}else{
				rlist.value[1].child.map(i=>{
					i.show = i.title.split('~')[1]>hm;
				})
			}
			if(hm>'24:00'){
				rlist.value[2].show=false;
			}else{
				rlist.value[2].child.map(i=>{
					i.show = i.title.split('~')[1]>hm;
				})
			}
		}else{
			rlist.value.map(i=>{
				i.show=true;
				i.child.map(it=>it.show=true)
			})
		}
		console.log(rlist.value)
		show.value = true;
	}
	
	
	const ctitle = ref('')
	function suredatetime(){
		if(!ctitle.value) return uni.$u.toast('请选择上门时间');
		form.value.reservtime = dlist.value[curd.value].name+' '+ ctitle.value
		show.value=false
	}
	

	const objs = ref('')
	// 商品信息
	function getinfo(){
		uni.$post({
			url: '/api/goods/swgoodslis',
			data: {
				aid: form.value.aid
			}
		}).then(res => {
			info.value = res.data.info;
			if(res.data.info.itionalmation?.length){
				let obj = {}
				res.data.info.itionalmation.map(i=>{
					obj[i] = ''
				})
				objs.value = obj;
				console.log(obj.value)
			}
		})
	}
	
	// 地址信息
	const ainfo = ref('')

	function setainfo(val) {
		console.log(val, 'ainfo')
		ainfo.value = val;
		form.value.did = val.id
	}
	// 获取默认地址信息
	function getainfo(){
		uni.$post({
			url:'/api/Address/dressselect',
			loading:false
		}).then(res=>{
			ainfo.value = res.data.find(i=>i.is_defult==1);
			form.value.did = ainfo.value.id;
			console.log(ainfo.value)
		})
	}

	const show = ref(false)
	const value = ref(1)
	const pay = ref(null)
	const ordersn = ref('')
	
	function sub() {
		if(!ainfo.value) return uni.$u.toast('请选择上门地址');
		if(!form.value.reservtime) return uni.$u.toast('请选择期望上门时间');
		if(!vinfo.value && !this.fileList1.length) return uni.$u.toast('请上传需求填报的视频或图片');
		if(!form.value.remark.trim().length) return uni.$u.toast('请输入需求填报内容');
		uni.$post({
			// 单商品 购物车
			url: '/api/Ordersystem/creatorder',
			data: {
				...form.value,
				itionalmation:objs.value,
				itionalmationimgs:itionalmationimgs.value
			}
		}).then(res => {
			ordersn.value = res.data;
			// pay.value.show = true;
			confirmpay()
		})
	}

	function confirmpay(val=2) {
		let obj = {
			0: 'money',
			1: 'alipay',
			2: 'wechat'
		}
		uni.$post({
			url: '/api/Ordersystem/payorder',
			data: {
				ordersn: ordersn.value,
				paytype: obj[val],
			}
		}).then(res => {
			if (val != 0) {
				uni.requestPayment({
					"provider": val == 2 ? "wxpay" : 'alipay',
					...res.data,
					success: (res) => {
						uni.$tt('支付成功', 'success');
						// uni.$delayBack()
					},
					fail: err => {
						uni.$tt('支付失败', 'error')
						// uni.$delayBack()
					},
					complete: () => {
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/Order/Detail?sn=' + ordersn.value
							})
						}, 1500)
					}
				})
			} else {
				uni.$tt(res.msg, 'success');
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/Order/Detail2?sn=' + ordersn.value
					})
				}, 1500)
			}
		}).catch(err=>{
			uni.$tt('服务端异常', 'error');
			setTimeout(() => {
				uni.redirectTo({
					url: '/pages/Order/Detail?sn=' + ordersn.value
				})
			}, 1500)
		})
	}



	const account = computed(() => {
		if (form.value.aid) {
			// 单个商品
			return (form.value.price * form.value.num - (cinfo.value?.price*1 || 0)).toFixed(2)
		} else {
			return 0;
		}
	})
	
	
	
	// 删除图片
	const deletePic = (event) => {
		const arr = ref([]);
		switch (event.name * 1) {
			case 1:
				arr.value = fileList1.value;
				break;
			case 2:
				arr.value = fileList2.value;
				break;
		}
		arr.value.splice(event.index, 1);
	};
	// 新增图片
	const afterRead = async (event) => {
		const arr = ref([]);
		switch (event.name * 1) {
			case 1:
				arr.value = fileList1.value;
				break;
			case 2:
				arr.value = fileList2.value;
				break;
		}
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = arr.value.length;
		lists.map((item) => {
			arr.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			let item = arr.value[fileListLen];
			arr.value.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
		}
	};
	
	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: baseUrl + '/api/Common/upload', // 仅为示例，非真实的接口地址
				filePath: url,
				name: 'file',
				header: {
					token: uni.getStorageSync('user').token
				},
				success: (res) => {
					setTimeout(() => {
						resolve(JSON.parse(res.data).data.fullurl)
					}, 1000);
				},
			});
		});
	};
</script>

<style>
	page {
		background: #f1f5f6;
	}

	.label {
		min-width: 96rpx;
		height: 36rpx;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		border: 2rpx solid #E24700;
		font-size: 22rpx;
		color: #E24700;
	}

	.skubox {
		height: 122rpx;
		background: #F5F5F5;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
	}

	.ltnum {
		width: 72rpx;
		padding: 0 10rpx;
		height: 38rpx;
		background: #FF6201;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		font-size: 24rpx;
		color: #FFFFFF;
		line-height: 38rpx;
		text-align: center;
	}
	
	
	.lbox{
		width: 322rpx;
		height: 92rpx;
		background: #E9E9E9;
		border: 2rpx solid #FFFFFF;
		font-size: 28rpx;
		color: #000000;
		text-align: center;
	}
	.lboxact{
		width: 322rpx;
		height: 92rpx;
		background: #FFFFFF;
		border: 2rpx solid #FFFFFF;
		font-weight: bold;
		font-size: 28rpx;
		color: #01796D;
		text-align: center;
	}
	
	.rbox{
		width: 376rpx;
		height: 92rpx;
		background: #FFFFFF;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		border: 2rpx solid #E9E9E9;
		font-size: 28rpx;
		color: #262626;
	}
	
	.rboxact{
		width: 376rpx;
		height: 92rpx;
		background: #FFFFFF;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		border: 2rpx solid #01796D;
		font-weight: bold;
		font-size: 28rpx;
		color: #01796D;
	}
	
	.pitems{
		height: 80rpx;
		background: #f8f8f8;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
		padding: 0 35rpx;
	}
	
	.cancel{
		width: 330rpx;
		height: 100rpx;
		background: #FFFFFF;
		border-radius: 50rpx 50rpx 50rpx 50rpx;
		border: 2rpx solid #E9E9E9;
		font-size: 32rpx;
		color: #A7A6A7;
	}
	
	.sure{
		width: 330rpx;
		height: 100rpx;
		background: #01796D;
		border-radius: 50rpx 50rpx 50rpx 50rpx;
		font-size: 32rpx;
		color: #FFFFFF;
	}
	
	
	.qt{
		width: 630rpx;
		height: 192rpx;
		background: #F3F3F3;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
	}
</style>